package com.feilong.edgeAI.speech;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import com.feilong.edgeAI.speech.util.AbilityConstant;
import com.iflytek.aikit.core.AeeEvent;
import com.iflytek.aikit.core.AiHandle;
import com.iflytek.aikit.core.AiHelper;
import com.iflytek.aikit.core.AiListener;
import com.iflytek.aikit.core.AiRequest;
import com.iflytek.aikit.core.AiResponse;
import com.iflytek.aikit.core.AiText;

import java.io.File;
import java.util.List;

/**
 * Created by【仿脑科技】
 *
 * @Author: potato
 * @CreateDate: 2023/12/19 15:02
 */
public class TransHelper implements AiListener {
    private static final String TAG = "TransHelper";
    private static String WORK_DIR = Environment.getExternalStorageDirectory().getAbsolutePath()// + File.separator + "niutrans"
            ;
    private String RES_DIR = AbilityInit.IFLYTEK_ROOT+File.separator+"itrans";
    private StringBuilder stringBuilder;
    private static AiHandle aiHandle;

    public void init() {
        AiHelper.getInst().registerListener(AbilityConstant.TRANS_ID, this);
        AiRequest.Builder engineBuilder = AiRequest.builder();
        engineBuilder.param("res_dir", RES_DIR + "/resource");
        engineBuilder.param("log_level", "2");
        engineBuilder.param("log_file", "/sdcard/.iflytek/itrans");

        int ret = AiHelper.getInst().engineInit(AbilityConstant.TRANS_ID, engineBuilder.build());
        if (ret != 0) {
            Log.d(TAG, "TransHelper engineInitFailed:" + ret);
            return;
        }
//        int ret = AiHelper.getInst().engineInit(AbilityConstant.TRANS_ID);
//        if (ret != AbilityConstant.ABILITY_SUCCESS_CODE) {
//            Log.w(TAG, "engineInit code ===>" + ret);
//        }
    }

    public static final String CNEN="cnen";
    public static final String ENCN="encn";
    private String type;
    private boolean translateState;
    private long start;
    private String currentText;
    @SuppressLint("LongLogTag")
    public void translate(String type, String text) {
        if(translateState){
            return;
        }
        currentText = text;
        this.type = type;
        stringBuilder = new StringBuilder();
        Log.d(TAG,"type="+type);
        final AiRequest.Builder paramBuilder = AiRequest.builder();
        String params = "type=" + type;//outfmt=json
        paramBuilder.param("params", params);
        paramBuilder.param("translateType", type);
        paramBuilder.text("txt", text);
        File file = new File(RES_DIR + "/resource");
        Log.d(TAG, "TransHelper : type="+type);
        Log.d(TAG, "TransHelper: 原文="+text);
        aiHandle = AiHelper.getInst().start(AbilityConstant.TRANS_ID, paramBuilder.build(), null);

        if (aiHandle.getCode() != 0) {
            Log.d(TAG, "TransHelper start失败:" + aiHandle.getCode());
            aiHandle = null;
            return;
        }
        translateState=true;
        start = System.currentTimeMillis();


        AiRequest.Builder dataBuilder = AiRequest.builder();
        //输入文本数据
        AiText input = AiText
                .get("txt")
                .data(text) //text为String类型输入文本
                .valid();
        dataBuilder.payload(input);

        int ret = AiHelper.getInst().write(dataBuilder.build(), aiHandle);
        //ret 值为0 写入成功；非0失败，请参照文档中错误码部分排查
        if (ret != 0) {
            Log.d(TAG, "TransHelper write失败:" + ret);
            aiHandle = null;
            return;
        }
        Log.d(TAG, "TransHelper write成功:" + ret);
    }
    @Override
    public void onResult(int handleID, List<AiResponse> outputData, Object usrContext) {
        //get output value
        if (null != outputData && outputData.size() > 0) {
            for (int i = 0; i < outputData.size(); i++) {
                byte[] bytes = outputData.get(i).getValue();
                if (bytes == null) {
                    continue;
                }
                String s = new String(bytes);
                stringBuilder.append(s);
                Log.d(TAG,
                        "TransHelper onResult:handleID:" + handleID + ":" + outputData.get(i).getKey() + "," + s);

            }
        }
    }

    @Override
    public void onEvent(int handleID, int event, List<AiResponse> eventData, Object usrContext) {
        Log.d(TAG, "TransHelper onEvent: "+event);
        if (event == AeeEvent.AEE_EVENT_END.getValue()) {
            Log.e(TAG, "TransHelper onEvent: result="+stringBuilder.toString());
            Log.d(TAG, "TransHelper onEvent: 用时="+(System.currentTimeMillis()-start));
            if(null!=onTranslateResultListener){
                onTranslateResultListener.onTranslate(currentText,stringBuilder.toString(),type);
            }
            AiHelper.getInst().end(aiHandle);
            translateState = false;
        }
    }

    @Override
    public void onError(int handleID, int err, String msg, Object usrContext) {
        Log.e(TAG, "TransHelper onError ERROR::" + msg + ",err code:" + err);
        if(null!=onTranslateResultListener){
            onTranslateResultListener.onError();
        }
        translateState=false;
    }

    private onTranslateResultListener onTranslateResultListener;

    public void setOnTranslateResultListener(TransHelper.onTranslateResultListener onTranslateResultListener) {
        this.onTranslateResultListener = onTranslateResultListener;
    }

    public interface onTranslateResultListener{
        void onTranslate(String original, String result,String type);
        void onError();
    }

}
